require(["common", "jQuery", "coAjax", "queryString", "href", "hash_routie"], function(jSouper, $, coAjax, QueryString, href, hash_routie) {
	var _num = 10;
	var _page = 0;

	hash_routie.on("bina", function() {
		_init_bina_config();
		_init_goods_data();
		_init_bina_goods();
	});
	//分页功能
	function _load_goods_page(num, page) {
		coAjax.get(appConfig.goods.list_with_page_info, {
			bus_id: busInfo._id,
			num: num,
			page: page
		}, function(result) {
			var info = result.result;
			console.log("bus.goods", info.goods);
			App.set("goods", info.goods);
			var page_info = {
				total_num: info.total_num,
				total_page: info.total_page,
				page: info.page,
				num: info.num
			};
			page_info._number_list = [];
			page_info._number_list.length = info.total_page;
			App.set("$Cache.bus.goods.page_info", page_info);
		});
	};

	//获取商品列表
	function _init_goods_data() {
		var queryString = new QueryString(location.hash);
		_num = queryString.get("num") || _num;
		_page = queryString.get("page") || _page;
		_load_goods_page(_num, _page);
	};
	//获取商品二进制配置
	function _init_bina_config() {
		coAjax.get(appConfig.bus.extend.bina.config, function(result) {
			App.set("$Cache.bina_buff", result.result);
		})
	};

	//获取二进制商品信息
	function _init_bina_goods() {
		coAjax.get(appConfig.bus.extend.bina.goods, function(result) {
			App.set("$Cache.bina.bina_list", result.result);
		});
	};

	//设定商品为二进制商品
	App.set("$Event.set_as_bina_goods", function(e, vm) {
		var goods_id_list = jSouper.map(App.get("$Cache.bina.bina_list"), function(bina_info) {
			return bina_info.goods._id;
		});
		goods_id_list.push(vm.get("_id"));
		vm.set("is_bina", true);
		coAjax.put(appConfig.bus.extend.bina.goods, {
			goods_id_list: goods_id_list
		}, function(result) {
			App.set("$Cache.bina.bina_list", result.result);
			_init_goods_data();
		});
	});
	//取消指定商品的二进制设定
	App.set("$Event.cancel_as_bina_goods", function(e, vm) {
		var goods_id_list = jSouper.map(App.get("$Cache.bina.bina_list"), function(bina_info) {
			return bina_info.goods._id;
		});
		var remover_id = vm.get("goods._id");
		goods_id_list = jSouper.filter(goods_id_list, function(goods_id) {
			return remover_id !== goods_id
		});
		coAjax.put(appConfig.bus.extend.bina.goods, {
			goods_id_list: goods_id_list
		}, function(result) {
			App.set("$Cache.bina.bina_list", result.result);
			_init_goods_data();
		});
	});
	//设定独立商品的分销比例
	App.set("$Event.open_edit_goods_bina_config", function(e, vm) {
		vm.set("$Private.$Cache.show_setting", true);
	});
	App.set("$Event.close_edit_goods_bina_config", function(e, vm) {
		vm.set("$Private.$Cache.show_setting", false);
	});
	App.set("$Event.use_custom_bina_id.toggle", function(e, vm) {
		if (vm.get("goods.use_custom_bina_id")) {
			App.get("$Event.set_custom_bina_config")(e, vm);
		} else {
			coAjax["delete"](appConfig.bus.extend.bina.remove_goods_custom_bina + vm.get("goods._id"), function(result) {
				vm.set(result.result);
			});
		}
	});
	App.set("$Event.bina.update_config", function() {
		coAjax.put(appConfig.bus.set_info_url, App.get("bus_loginer.info"), function(result) {
			App.set("bus_loginer", result.result);
			alert("success", "配置修改成功");
		});
	});
	App.set("$Event.set_custom_bina_config", function(e, vm) {
		var buff_config = vm.get("goods_custom_bina_buff.config") || {};
		buff_config.first = parseFloat(buff_config.first) || 0;
		buff_config.second = parseFloat(buff_config.second) || 0;
		buff_config.third = parseFloat(buff_config.third) || 0;
		coAjax.put(appConfig.bus.extend.bina.set_goods_custom_bina + vm.get("goods._id"), buff_config, function(result) {
			vm.set(result.result);
		});
	});
	//获取某分销商品的可进行分销的用户列表
	App.set("$Event.get_user_list_of_bina", function(e, vm) {
		var bina_id = vm.get("bina._id");
		coAjax.get(appConfig.bus.extend.bina.get_user_list_of_bina + bina_id, function(result) {
			App.set("$Cache.user_list_of_bina." + bina_id, result.result);
			vm.set("$Private.$Cache.user_list_of_bina", result.result);
		});
	});


	function _format_data(data) {

		var array_data = Object.keys(data).map(function(user_id) {
			return data[user_id];
		});

		var ec_data = [];

		array_data.forEach(function(bind_item) {
			//有父亲，不记录
			if (bind_item.recommender_id && data[bind_item.recommender_id]) {
				return
			} else { //顶级节点，遍历获取
				ec_data = ec_data.concat({
					name: bind_item.user_id,
					children: function _f(p_id) {
						return array_data.filter(function(a_bind_item) {
							return a_bind_item.recommender_id == p_id
						}).map(function(b_bind_item) {
							return {
								name: b_bind_item.user_id,
								children: _f(b_bind_item.user_id)
							}
						});
					}(bind_item.user_id)
				});
			}
		});

		ec_data = [{
			name: "商品二进制分享关系网",
			children: ec_data
		}];
		return ec_data;
	};

	function _echarts_run_code() {
		require(
			[
				'echarts',
				'echarts/chart/tree' // 使用柱状图就加载bar模块，按需加载
			],
			function(ec) {
				// 基于准备好的dom，初始化echarts图表
				var myChart = ec.init(document.getElementById('main'));

				var option = {
					title: {
						text: "__echarts_title__"
					},
					toolbox: {
						show: true,
						feature: {
							mark: {
								show: true
							},
							dataView: {
								show: true,
								readOnly: false
							},
							restore: {
								show: true
							},
							saveAsImage: {
								show: true
							}
						}
					},
					series: [{
						name: '树图',
						type: 'tree',
						orient: 'horizontal', // vertical horizontal
						rootLocation: {
							x: 100,
							y: 230
						}, // 根节点位置  {x: 100, y: 'center'}
						nodePadding: 8,
						layerPadding: 200,
						hoverable: false,
						roam: true,
						symbolSize: 6,
						itemStyle: {
							normal: {
								color: '#4883b4',
								label: {
									show: true,
									position: 'right',
									formatter: "{b}",
									textStyle: {
										color: '#000',
										fontSize: 5
									}
								},
								lineStyle: {
									color: '#ccc',
									type: 'curve' // 'curve'|'broken'|'solid'|'dotted'|'dashed'

								}
							},
							emphasis: {
								color: '#4883b4',
								label: {
									show: false
								},
								borderWidth: 0
							}
						},

						data: __echarts_data__
					}]
				};

				// 为echarts对象加载数据 
				myChart.setOption(option);
			}
		);
	};
	App.set("$Event.show_bina_user_map", function(e, vm) {
		var user_map = vm.get("bina.user_map");

		var code = _echarts_run_code.toString()
		code = code.substring(code.indexOf("{") + 1, code.length - 1)
		code = code.replace("__echarts_title__", vm.get("goods.goods_name") + " 的分销关系网").replace("__echarts_data__", JSON.stringify(_format_data(user_map)));

		// var bina_user_map_node = $("#bina_user_map_node").attr("src", "__dotnar_lib_base_url__/echarts.html?_=" + Math.random())[0];
		// if (!messenger) {
		// 	messenger = new Messenger('Parent', 'ECharts-Run-Code');
		// 	messenger.addTarget(bina_user_map_node.contentWindow, "echarts-base-iframe");
		// }
		// bina_user_map_node.onload = function() {
		// 	messenger.send("RUN_SCRIPT" + code);
		// }
		var project_name = 'ECharts-Run-Code:' + vm.get("bina._id");
		var bina_user_map_window = window.open("__dotnar_lib_base_url__/echarts.html?project_name=" + encodeURIComponent(project_name));
		var messenger = new Messenger('Parent', project_name);
		messenger.addTarget(bina_user_map_window, "echarts-base-iframe");
		messenger.listen(function(msg) {
			if (msg === "WINDOW-ONLOAD") {
				console.log("bina_user_map_window load, send draw code.");
				messenger.send("RUN_SCRIPT" + code);
			}
		});
	});
	App.set("$Event.add_user_to_bina", function(e, vm) {
		var bina_id = vm.get("$Caller.bina._id");
		coAjax.post(appConfig.bus.extend.bina.add_user_to_bina + bina_id, {
			user_maybe_info: vm.get("user_maybe_info_to_add")
		}, function(result) {
			vm.set("user_maybe_info_to_add", "");
			vm.set("user_list_of_bina", result.result);
		});
	});

	//修改商品二进制设置
	App.set("$Event.bina_buff.edit", function() {
		App.set("$Cahcs.bina_buff.editing", true);
	});
	App.set("$Event.bina_buff.upload", function() {
		var new_config = App.get("$Cache.bina_buff.new_config");
		var old_config = App.get("$Cache.bina_buff.config");
		if (!new_config) {
			App.get("$Event.bina_buff.cancle")();
			return;
		}
		coAjax.put(appConfig.bus.extend.bina.config, {
			first: new_config.first || old_config.first,
			second: new_config.second || old_config.second,
			third: new_config.third || old_config.third
		}, function(result) {
			App.set("$Cache.bina_buff", result.result);
			App.get("$Event.bina_buff.cancle")();
		});
	});
	App.set("$Event.bina_buff.cancle", function() {
		App.set("$Cahcs.bina_buff.editing", false);
		App.set("$Cache.bina_buff.new_config", null);
	});
});